<?php
//生成订单号
function creatorder(){
	$order_id_main = date('YmdHis') . rand(10000000,99999999);

  	$order_id_len = strlen($order_id_main);

  	$order_id_sum = 0;

  	for($i=0; $i<$order_id_len; $i++){

  	$order_id_sum += (int)(substr($order_id_main,$i,1));

  	}
  	return  $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
}



//加载数据库框架
function mdb($configName = 'mdb'){
	if(isset($GLOBALS['mdb']))return $GLOBALS['mdb'];
	m('m/Medoo');
	return $GLOBALS['mdb']=new Medoo\Medoo(M['mdb']);
}
//简写格式化输出
function p($var, $type = false){if($type){var_dump($var);}else{print_r($var);}}
//json api模式
function jsonMsg($Msg){
	header('Content-type:text/json');
	die(json_encode($Msg,JSON_UNESCAPED_UNICODE));
}
//加密解密函数
function lockString($string,$operation,$key='mtfy'){
		if($operation=='D'){$string=str_replace(array('-01.-','-02.-','-03.-'),array('%','/','+'),$string);}
		$key=md5($key);
		$key_length=strlen($key);
		$string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
		
		$string_length=strlen($string);
		$rndkey=$box=array();
		$result='';
	for($i=0;$i<=255;$i++){
		$rndkey[$i]=ord($key[$i%$key_length]);
		$box[$i]=$i;
		}
	for($j=$i=0;$i<256;$i++){
		$j=($j+$box[$i]+$rndkey[$i])%256;
		$tmp=$box[$i];
		$box[$i]=$box[$j];
		$box[$j]=$tmp;
	}
	for($a=$j=$i=0;$i<$string_length;$i++){
		$a=($a+1)%256;
		$j=($j+$box[$a])%256;
		$tmp=$box[$a];
		$box[$a]=$box[$j];
		$box[$j]=$tmp;
		$result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
	}
	if($operation=='D'){
		if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
			return substr($result,8);
		}else{
			return'';
		}
	}else{
		return str_replace(array('=','%','/','+'),array('','-01.-','-02.-','-03.-'),base64_encode($result));
	}
}

//获得视图的url地址，用于include
function showTpl($tplName = null,$type = true){
	if(gettype($tplName)=='boolean'){$type = $tplName;$tplName = null;}
	//获得文件的缓存目录
	$cacheDir=M_PATH;
	//获得文件的名称
	if(M['TemplateType'] == 'file'){
		$Url = is_null($tplName) ? M_PATH.M_C.'_'.M_M.'.html' : $tplName.'.html';
	}else{
		$Url = is_null($tplName) ? M_PATH.M_C.M['Ds'].M_M.'.html' : $tplName.'.html';
	}
	//真实文件地址
	$tplUrl=M['App'].M['TemplateDir'].M['Ds'].$Url;
	//解析模板
	if($type){
		$tplconf['tplstart']=M['tpl']['tplstart'];
		$tplconf['tplend']=M['tpl']['tplend'];
		$tplconf['tplcachetime']=M['tpl']['tpltime'];
		$tplconf['tplcacheDir']=M['App'].M['CacheDir'].M['Ds'].M['tpl']['tplcachedir'].M['Ds'];
		$tplconf['tpltemplateDir']=M['App'].M['TemplateDir'].M['Ds'];
		//判断缓存时间
		if(M['tpl']['tpltime']<0) {goto end;}
		$cachefile=M['App'].M['CacheDir'].M['Ds'].M['tpl']['tplcachedir'].M['Ds'].$Url;
		$cachefiletime=@filemtime($cachefile);
		if(($cachefiletime+M['tpl']['tpltime'])>time()) {
			Return $cachefile;
		}else {
			//解析模板
			m('m/tpl');
			$tplUrl =(new tpl($tplconf))->geturl($tplUrl,true,$cachefile,true);
		}
	}
	end:
	if(is_file($tplUrl)){return($tplUrl);}
}
//session 
function startSession(){
	switch(M['session']['type']){
		case 'memcache' :
			ini_set("session.save_handler", "memcache");
			ini_set("session.save_path", M['session']['port']);
		break;
		case 'redis':
			ini_set("session.save_handler", "redis");
			ini_set("session.save_path", M['session']['port']);
		break;
		default:
			if(!is_dir(M['App'].M['CacheDir'].M['Ds'].M['session']['dir'].M['Ds'])){mkdir(M['App'].M['CacheDir'].M['Ds'].M['session']['dir'].M['Ds'], 0777, true);}
			session_save_path(M['App'].M['CacheDir'].M['Ds'].M['session']['dir'].M['Ds']);
	}
	session_start();
	session_write_close();
}

//设置 session
function setSession($name, $val){
	@session_start();
	$_SESSION[$name] = $val;
	session_write_close();
}

//获取 session
function getSession($name){if(isset($_SESSION[$name])){return $_SESSION[$name];} return null;}

//销毁指定的session
function removeSession($name){
	if(empty($_SESSION[$name])){return null;}
	session_start();
	unset($_SESSION[$name]);
	session_write_close();
}
// 设置 cookie
function setCook($name, $val, $expire = 31536000){
	$expire += time();
	@setcookie($name, $val, $expire, '/');
	$_COOKIE[$name] = $val;
}

//获取 cookie
function getCook($name){if(isset($_COOKIE[$name])){return $_COOKIE[$name];} return null;}

//删除 cookie
function remCook($name){
	setcookie($name, 'null', time() - 1000, '/');
}
//数据缓存
function getCache(){
	if($GLOBALS['cache']){return $GLOBALS['cache'];}
	m('m/'.M['cache']['type'].'Cacher');
	$GLOBALS['cache'] = (M['cache']['type'].'Cacher')::getInstance(M['cache']);
}
function cache($name,$queryMethod='',$data='',$update=false, $timer = 3600,$isSuper = true){
	if(M['cache']['start']==false){return is_object($queryMethod)?(empty($data)?$queryMethod():$queryMethod($data)):$queryMethod;}
	getCache();
	global $cache;
	$cacheName = $isSuper ? $name : M_C.'_'.M_M.$name;
	$cacheName = md5($cacheName);
	if($update){goto set;}
	$cachedRes = $cache->get($cacheName);
	if($cachedRes){return $cachedRes;}
	set:
	echo('set');
	$queryRes =is_object($queryMethod)?(empty($data)?$queryMethod():$queryMethod($data)):$queryMethod;
	$cache->set($cacheName, $queryRes, $timer);
	return $queryRes;
}
function clearCache(){
	getCache();
	global $cache;
	$cache->clearCache();
}
function removeCache($name, $isSuper = true){
	getCache();
	global $cache;
	$cacheName = $isSuper ? $name : M_C.'_'.M_M.$name;
	$name = md5($name);
	$cache->removeCache($name);
}

//去除空白字符
function trimAll($str){
    $qian=array(" ","　","\t","\n","\r");
    $hou=array("","","","","");
    return str_replace($qian,$hou,$str); 
}
//获得地址后参数
function M_getPath(){
    if (isset($_SERVER['HTTP_X_ORIGINAL_URL'])) {
        $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL'];
    }elseif(isset($_SERVER['HTTP_X_REWRITE_URL'])) {
        $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
    }elseif(isset($_SERVER['HTTP_REQUEST_URI'])) {
        $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_REQUEST_URI'];
    }
    return $_SERVER['REQUEST_URI'];
}

//判断是否手机
function M_isMobile(){
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])){Return true;}
    if(!isset($_SERVER['HTTP_USER_AGENT'])) {Return false;}
    $waparray=array('android','iphone','ipad','mobile');
    foreach($waparray as $thisphone) {
        if(stripos($_SERVER['HTTP_USER_AGENT'],$thisphone)===false) {}else {
            Return true;
        }
    }
    Return false;
}
//错误页面
function M_err($title,$msg='',$icon='3',$url=1,$btn='确定'){
    switch ($icon) {
        case 1:$icon='weui-icon-success weui-icon_msg';break;
        case 2:$icon='weui-icon-info weui-icon_msg';break;
        case 3:$icon='weui-icon-info weui-icon_msg-primary';break;
        case 4:$icon='weui-icon-warn weui-icon_msg';break;
        case 5:$icon='weui-icon-waiting weui-icon_msg';break;
        default:$icon='weui-icon-warn weui-icon_msg-primary';break;
    }
    switch($url){
        case 1:$url='javascript:history.go(-1)';break;
        case 2:$url='javascript:location.reload()';break;
    }
    include(M_IN.'templates'.M_DS.'err.php');
    exit;
}
//获得ip
function M_ip() {
    if(isset($_SERVER)){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $arr = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($arr as $ip){
                $ip = trim($ip);
                if ($ip != 'unknown'){$realip = $ip; break;}
            }
        }elseif(isset($_SERVER['HTTP_CLIENT_IP'])){
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }else{
            if (isset($_SERVER['REMOTE_ADDR'])){
                $realip = $_SERVER['REMOTE_ADDR'];
            }else{
                $realip = '0.0.0.0';
            }
        }
    }else{
        if (getenv('HTTP_X_FORWARDED_FOR')){
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }elseif (getenv('HTTP_CLIENT_IP')){
            $realip = getenv('HTTP_CLIENT_IP');
        }else{
            $realip = getenv('REMOTE_ADDR');
        }
    }
    preg_match("/[\d\.]{7,15}/",$realip,$onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
    return $realip;
}

//获取顶级域名
function M_topHost($url,$type=0){
    if(!$url){return FALSE;}
    $url   = strtolower($url); //首先转成小写
    $hosts = parse_url($url);
    if($type==0){
        $host  = $hosts['path'];
    }else{
        $host  = $hosts['host'];
    }
    //查看是几级域名
    $data = explode('.', $host);
    $n    = count($data);
    //判断是否是双后缀
    $preg = '/[\w].+\.(com|net|org|gov|edu)\.cn$/';
    if (($n > 2) && preg_match($preg, $host)) {
        //双后缀取后3位
        $host = @$data[$n - 3] . '.' . @$data[$n - 2] . '.' . @$data[$n - 1];
    } else {
        //非双后缀取后两位
        $host = @$data[$n - 2] . '.' . @$data[$n - 1];
    }
    return $host;
}

/***自定义函数***/
//随机生成数
function M_rand( $length = 6,$type=1) {

    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $password = '';
    for ( $i = 0; $i < $length; $i++ ) {
        $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }
    return $password;
}
// run log
function M_runLog(){
    if(!M['Debug']){return false;}
    $cost = M_cost();
    echo '<script>console.log("MTFY Log : 控制器 : '.M_C.
        ', 方法 : '.M_M.' - 运行时间 : '. $cost[0] .'毫秒, 占用内存 : ' . $cost[1] .'k");</script>';
}
/**
 * 时间、内存开销计算
 * @return array(耗时[毫秒], 消耗内存[K])
 */
function M_cost(){
    return array(
        round((microtime(true) - M_START_TIME) * 1000, 2),
        round((memory_get_usage() - M_START_MEMORY) / 1024, 2)
    );
}
?>